define(["moment"], function (moment) {
	return ["$scope", "$filter", "$stateParams", "MMWService", "config", "$calculater", "$translate", "$timeout", '$LogService', '$mdDialog',
	function ($scope, $filter, $stateParams, $MMWService, config, $calculater, $translate, $timeout, $LogService, $mdDialog) {
		$scope.init = function(){
			            // 20231002 modify by Alan for#145964 : 重設$MMWService.needLogout()卡控
			config.cache.isWaitingLogout = false;
			$scope.userInfo = {
				account : config.setting.account,
				password: config.setting.password,
				ic_card: ""
			}
			$scope.$root.subMenu=undefined;
			$scope.environment = config.setting.environment;
			$scope.environment_display = $filter('translate')('Login.env.' + config.setting.environment);
			$scope.device = config.cache.device;
			$scope.isIPad = false; 
			//20200506 新增載入測試區與正式區 modify by Oliver
			var login_info = JSON.parse(localStorage.getItem('SMES_setting'));
			if(login_info && login_info != ''){
				if(login_info.environment=='Test'){
					$scope.active=false;
				}else if(login_info.environment=="Production"){
					$scope.active=true;
				}
			}else{
				$scope.active=false;//沒有localstorage預設進入正式區
			}
			//20210316 Modify by德義家興for #0084096: 众捷：后端密码原则对前端无效
			$scope.PasswordRule_WrongNum = '1'; //系統設定 允許密碼錯誤的上限
			$scope.login_error_count = 0; //密碼錯誤的次數

			$scope.can_you=true;

			//20211008 Modify by Jason for M#0100957: IOS登入跑版問題
			//如果為ipad調整css
			if(navigator.userAgent.match(/(iPad)/))
			{
				$scope.isIPad = true; 
			}

			$timeout(function(){
				$scope.showLogin = true;
		    	$timeout(function(){
					try{
						$scope.$root.hideMenu();
						$scope.version = getVersion(config.appVersion);
					}catch(e){}
		    		try{
						componentHandler.upgradeAllRegistered();
						if(!window.cordova){
							if(config.setting.scanBarcod == "Y"){
								document.getElementById('c_icinfor').focus();
							} else {
								document.getElementById('account').focus();
							}
						
						} else {
							$scope.$root.OpenBackgroundService();
							if(config.setting.scanBarcod == "Y"){
								document.getElementById('c_icinfor').focus();
							} else {
								document.getElementById('account').focus();
							}
						}
						angular.element(document.getElementById('loginPanel')).css("opacity", "1");
		    			navigator.splashscreen.hide();
		    		}catch(e){
		    			console.log(e);
		    		}
                    try{
						chrome.passwordsPrivate.getSavedPasswordList(function(passwords) {
							if(passwords){
								for(var i =0; i<passwords.length;i++){
									chrome.passwordsPrivate.removeSavedPassword(i);
								}
							}
						});
					}catch(e){}
					// 20240426 add by wenwei for M#162555: 雅典娜单点登陆
					if (localStorage.getItem('AthenaLoginParameter') != null){
						$MMWService.sendToServer({
							uri: 'ServicesSTD.Module_SYS.Athena_AutoLogin',
							content: { parameters: JSON.parse(localStorage.getItem('AthenaLoginParameter')) },
							success: function(data) {
								$scope.userInfo.account = data.UserModel.VerifyUserId
								$scope.userInfo.password = data.UserModel.Password
								$scope.login()
								localStorage.removeItem('AthenaLoginParameter')
							}
						})
					// 自動登入
					} else if($stateParams.data.notLogin == undefined && config.setting.autoLogin == 'Y'){
						$scope.login();
					}
		    	});
			});
		}

		$scope.login = function(){
			if($scope.userInfo.account=='' || $scope.userInfo.password==''){
				$scope.$root.showAlert($filter('translate')('Login.msg'));
			} else if (validateInput($scope.userInfo.account) && validateInput($scope.userInfo.password)) {
                //20190211 modify by Dustdusk for M#54899: 登入時檢查是否需要清除log
                $LogService.DeleteLogFiles();

				//登入
				config.cache.loginTime = new Date(); //20170210 add by Dustdusk;
				config.cache.account = $scope.userInfo.account.toUpperCase();
				// 20231017 modify by shiwl for M# 0147716: 前端密码传值是明文，AD账户验证时为什么还要反解析？
				config.cache.password = $scope.userInfo.password;
				// 重設自動跳轉
				$scope.$root.isAutoRouting = config.setting.defaultProgram !== '';
				login(function(data){
					//$scope.$root.reciprocalStart();//開始登出倒數
					config.cache.name = data.employee_name;
					// 20190506 modify by Dustdusk for M#57176:登入時帶回後台目前全部的系統參數
					// 20220408 modify by Alan for#109776 : 對系統參數作預處理
					config.cache.sys_parameter = parameterPreprocess(data.sys_parameter);
					// 20230303 modify by Alan for#: module_setting卡控
					config.cache.module_setting = data.module_setting || {};
					if(config.setting.workstating_mode == 'Y'){
						// 20231207 modify by Alan for#144154 : 工位機模式預設作業依照權限設定控制
						// 工位機模式預設作業
						let defaultProgram = ['E01', 'E08', 'B0202', 'B0203'];
						config.cache.permissions = data.user_permissions_info_get.filter(program => defaultProgram.includes(program));
					} else if(data.employee_level != '0'){
						// 20230210 modify by Alan for#127474 : 修正登入報錯
						config.cache.permissions = data.user_permissions_info_get;
					} else {
						config.cache.permissions = undefined;
					}
					// 更新menu，畫面跳轉
					dynamic_menu_info_get(function(data) {
						$scope.showLogin = false;
						var target = config.cache.device == 'phone' ? 'menu' : 'home';
						$scope.$root.changeProgram(target);
					});
				});
			}
        }
		// 20231025 add by wenwei for M#139027: [sMES]H5 帳號使用全形字登入沒有卡控[台灣積層]
		function validateInput(input) {
			// 使用正则表达式匹配是否包含全角字符
			var regex = /[Ａ-Ｚａ-ｚ０-９]/;
			if (regex.test(input)) {
				$scope.$root.showAlert($filter('translate')('Login.error.fullhalf_error'));
			} else{
				return true
			}
		}

		function login(callback){
			var _user_type = 'Normal';
			if(config.cache.device == 'phone' || config.setting.workstating_mode == 'Y')
				_user_type = 'Light';

			$MMWService.sendToServer({
				uri : 'ServicesSTD.Module_SYS.user_permissions_info_get_json',
				content : {
					user_type:_user_type
				},
				msg : 'Login.msg.logining',
				success : function(data){ //正確登入or受控制的錯誤

                                   $scope.DispatchModel =  data.sys_parameter.DispatchModel;
                                         
					//20210316 Modify by德義家興for #0084096: 众捷：后端密码原则对前端无效
					//取得 密碼錯誤可嘗試的次數
					if (data.sys_parameter['PasswordRule.WrongNum'] != undefined) { //有設定上限
						$scope.PasswordRule_WrongNum = data.sys_parameter['PasswordRule.WrongNum']; //物件屬性的名稱包含'.',用陣列方法取值
					}else{
						$scope.PasswordRule_WrongNum = '999';
					}
					
					//error_code:0 正常登入(原邏輯)
					// 20210409 modify by 奕達 for M#84096 : 後端沒回傳error_code 走原登入
					if (data.error_code == 0 || data.error_code == undefined) {
						config.mdssessionno = data.login_session_id;
						if(callback)
							callback(data);
					//314:執行過程中缺少必要資料，請重新確認資料完整性 密碼到期跑這個邏輯
					}else if (data.error_code == 314) {
						// 20220518 modify by Alan for#110548 : 修正錯誤訊息屬性名稱
						$scope.$root.showConfirm(data.error_message, function (dialog) {
							dialog.hide();
							$mdDialog.serviceDialog('PasswordService'); //修改密碼
						});
					//310:帳號驗證失敗
					} else if (data.error_code == 310) {
						if (data.sys_parameter['PasswordRule.WrongNum'] != undefined) { //有設上限才增加錯誤次數
							$scope.login_error_count++;
						}
						if($scope.login_error_count < $scope.PasswordRule_WrongNum){ //低於上限
							$scope.$root.showAlert($filter('translate')('Login.error.ap'));							
						}else{ //超過上限
							$scope.$root.showConfirm($filter('translate')('Login.error.password_error1') + '<br>'
								+ $filter('translate')('Login.error.password_error2') + $scope.login_error_count,
								function (dialog) {
									$scope.back();
								});	
						}
					//其他未特別處理的錯誤
					}else{
						$scope.$root.showAlert(data.error_message, {
							level: 'error',
							error_detail: {
								Code: data.error_code,
								uri: 'ServicesSTD.Module_SYS.user_permissions_info_get_json',
								Exception: data.exception_message,
								StackTrace: data.stack_trace
							}
						});
					}
				},
				error : function(data, errorBack){
						errorBack(data);
				}
			});
			/*
			// 20201215 modify by 外包 for M#83491: 添加布局缓存
			$MMWService.sendToServer({
			    uri: 'ServicesSTD.Module_SYS.layout_info_get',
			    content: {},
			    success: function (data) {
			        if (data.layoutList.length > 0) {
			            localStorage.setItem('customLayout', JSON.stringify(data.layoutList));
			        } else {
			            localStorage.removeItem('customLayout');
			        }
			    }
			});
			*/
		}
        function dynamic_menu_info_get(callback) {
            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_SYS.dynamic_menu_info_get',
                success : function(data){
					// 20230912 modify by wewei for M#145816 當第一層menu與第二、三層menu對應不起來時，提示權限錯誤
					if (Object.keys(data).length == 0) {
						$scope.$root.showAlert($filter('translate')('Login.error.permission_error',{account:$scope.userInfo.account}))
						return
					}
					// 20230303 modify by Alan for#: module_setting卡控
					// 手機版走舊版菜單設定
					if (config.cache.device != 'phone') {
						var menu = data.filter(menu => {
							// 自定义报表會跳提示訊息，所以不關
							if(menu.name === 'modelC'){
								return true;
							} else if(menu.platform === 'Pad' && menu.menus.length != 0) {
								return true;
							}
						});
						var menuFormat = menuParser(menu, config.oriMenu);
						//config.oriMenu = config.menu;
						config.menu = angular.merge([], menuFormat);
					}
                    if(typeof callback === 'function') {
                        callback(data);
                    }
                },
				error: function(error) {
					$scope.$root.showAlert($filter('translate')('Login.error.permission_error',{account:$scope.userInfo.account}))
				}
				// 20231027 delete by wenwei for M#148913: 前端登入報錯，提示訊息不友善，不好排查
            });
        }


         
      
        // 解析menu轉為前端格式
        function menuParser(source, ori) {
        // 20230323 Modify by shiwl 派工作业和多日派工通过配置端控制展示、
             
         source.forEach(item=>{
                if(item.name == "moduleA"){
                     item.menus.forEach(flag=>{
                     if(flag.name == "modelA02"){
                        if($scope.DispatchModel ==1){
                               flag.default = "A08";
                        }
                        flag.menus.forEach(menuItem =>{
                           if( menuItem.name=="A08" && $scope.DispatchModel ==0){
                               menuItem.isShown = false; 
                           }
                           if( menuItem.name=="A07" && $scope.DispatchModel ==1){
                        
                               menuItem.isShown = false; 
                           }
                      })
                     } 
                 })    
                }                                       
               });


            source.forEach(element => {
				//20221227 modify by Dustdusk for M#: 增加使用formName取代name
				element.name = element.formName||element.name;
				let oriElement = ori.find(_c => _c.name == element.name);
                // 當子選單為0時，把自己設為預設作業
                if(element.menus && element.menus.length === 0) {
                    element.default = element.name;
                }
                if(element.menus && element.menus.length > 0) {
                    element.childs = element.menus;
                    delete element.menus;
                    element.childs = menuParser(element.childs, (oriElement||{}).childs||[]);
                }
                element.isShow = element.isShown === 'Y';
                element.title = element.displayText;
                element.icon = element.icon || 'W_Com_Report_nor_32';
                //element.icon_cli = element.icon_cli || 'W_Com_Report_sel_32';
				if(oriElement != undefined) {
				    element.tag = oriElement.tag;
				    element.isReport = oriElement.isReport;

					element.icon_cli = oriElement.icon_cli;
					element.icon_s = oriElement.icon_s;
					element.color = oriElement.color;
				} else {
					element.icon_cli = element.icon || 'W_Com_Report_sel_32';
				}
            });

            return source;
        }

        $scope.setting = function(){
			$scope.$root.changeProgram('setting', {parent : 'login'});
        }

        $scope.autoFocus = function(id){
			document.getElementById(id).focus();
        };

        $scope.nextFocus = function(event, id){
			if(event.keyCode == 13 && validateInput($scope.userInfo.account)){
				$scope.autoFocus(id);
			}
        }

        $scope.autoLogin = function(event){
        	if(event.keyCode == 13 && validateInput($scope.userInfo.password)){
				//20210316 Modify by德義家興for #0084096: 众捷：后端密码原则对前端无效
				if ($scope.login_error_count < $scope.PasswordRule_WrongNum) { //檢查是否超過密碼錯誤次數上限
					event.currentTarget.blur();
					$scope.login();
				}
			}
        }

        $scope.back = function(){
            $scope.$root.showConfirm($filter('translate')('Login.msg.is_exist'),function(dialog){
                if($scope.$root.isCordova){
                    navigator.app.exitApp();
                } else {
        			try{
						// 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
						const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
        				remote.getCurrentWindow().close();
        			} catch(e){
        				nodeRequire('nw.gui').App.quit();
        			}
                }
            });
        }

		$scope.loadServerList = function(){
			var serverList = [];
			if(config.serverList){
				for(var env_name in config.serverList){
					serverList.push({code:env_name, label:$filter('translate')('Login.env.'+env_name), server:config.serverList[env_name]});
				}
			}
			$scope.$root.showSelect({
				title : $filter('translate')('Login.ServerList'),
				label : 'label',
				code : 'code',
				selectCode : '',
				list : serverList,
				confirm : function(item, dialog){
					dialog.hide();
					config.setting.environment = $scope.environment = item.code;
					config.server.name = item.server.name;
                    config.server.SMES_name = item.server.SMES_name;
					$scope.environment_display = $filter('translate')('Login.env.' + config.setting.environment);
					if (typeof(Storage) !== "undefined") {
						localStorage.setItem(config.appName + "_server", JSON.stringify(config.server));
						localStorage.setItem(config.appName + "_setting", JSON.stringify(config.setting));
						//localStorage.setItem(config.appName + "_lang", $scope.currentUse);
					}
				}
			});
		}

		$scope.getLogo = function(){
			return {'background-image': 'url("image/APP_logo_'+config.setting.lang + '.png")'};
		};

		$scope.showFocus = function(target){
			$('.' + target).focus();
		}

		//20200506 新增載入測試區與正式區 modify by Oliver
		$scope.change_env=function(){
			if($scope.active){
				config.setting.environment = $scope.environment = 'Test';
				config.server.name = 'SMES_Test_Services';
				config.server.SMES_name = 'SMES_Test_MESws_STD';
			}else{
				config.setting.environment = $scope.environment = 'Production';
				config.server.name = 'SMES_Production_Services';
				config.server.SMES_name = 'SMES_Production_MESws_STD';
			}
			$scope.environment_display = $filter('translate')('Login.env.' + config.setting.environment);
			if (typeof(Storage) !== "undefined") {
				localStorage.setItem(config.appName + "_server", JSON.stringify(config.server));
				localStorage.setItem(config.appName + "_setting", JSON.stringify(config.setting));
				//localStorage.setItem(config.appName + "_lang", $scope.currentUse);
			}
			$scope.active=!$scope.active;
		}

		//20200506 新增載入測試區與正式區 modify by Oliver
		$scope.change_env=function(){
			if($scope.active){
				config.setting.environment = $scope.environment = 'Test';
				config.server.name = 'SMES_Test_Services';
				config.server.SMES_name = 'SMES_Test_MESws_STD';
			}else{
				config.setting.environment = $scope.environment = 'Production';
				config.server.name = 'SMES_Production_Services';
				config.server.SMES_name = 'SMES_Production_MESws_STD';
			}
			$scope.environment_display = $filter('translate')('Login.env.' + config.setting.environment);
			if (typeof(Storage) !== "undefined") {
				localStorage.setItem(config.appName + "_server", JSON.stringify(config.server));
				localStorage.setItem(config.appName + "_setting", JSON.stringify(config.setting));
				//localStorage.setItem(config.appName + "_lang", $scope.currentUse);
			}
			$scope.active=!$scope.active;
		}

		function getVersion(version){
			var versionArray = version.split('.');
			var newVersion = undefined;
			var limit = (versionArray.length > 3)?3:versionArray.length;
			for(var i = 0; i < limit; i++){
				if(newVersion){
					newVersion += '.'+versionArray[i];
				} else {
					newVersion = versionArray[i];
				}
			}
			return newVersion;
		}



	    //add by linzh for M#71988 ------------------------------------start----------------------------------------------------------
		$scope.ICCardScanner = function () {
		    $scope.$root.OpenScanner({
		        after: function (result) {
		            $timeout(function () {
		                $scope.userInfo.ic_card = result.text;
		                icLogin();
		            });
		        },
		        exception: function () {
		            //目前裝置無法使用相機
					$scope.$root.showAlert($filter('translate')('common.msg.cant_use_camera'));
		        },
		        orientation: 'landscape'
		    });
		}

		$scope.icLogin = function (event) {
		    if (event.keyCode == 13) {
		        //此处将IC卡信息传给后台接口，返回登录人帐号密码等信息
		        icLogin();
		    }
		}

		function icLogin() {
		    var content = {
		        IcNo: $scope.userInfo.ic_card
		    }
		    $MMWService.sendToServer({
		        //uri: 'ServicesSTD.Module_SYS.ic_card_info_get',
				uri: 'ServicesCUS.Module_CUS.ic_card_info_get_C',
		        content: content,
		        msg: 'Login.msg.getUserInfo',
		        success: function (data) {
					if (data.UserNo != null) {
		                $scope.userInfo.account = data.UserNo;
						// 如果不启用IC卡密码，则不自动登录		       
						if (data.PassWord != null && data.PassWord != "") {
							$scope.userInfo.password = data.PassWord;
							$scope.login();//调用登陆按钮的方法
						}
						else {
							document.getElementById('password').focus();
						}
		            }
		            else {
		                $scope.$root.showAlert($filter('translate')('Login.error.ic_card_error'));
		            }
		        }
		    });
		}
	    //add by linzh for M#71988 ------------------------------------end----------------------------------------------------------

		$scope.environment = function() {
			environment == "Production"
		}
		
		// 20220408 modify by Alan for#109776 : 對系統參數作預處理
		function parameterPreprocess(parameter) {
			if(!parameter) { 
				return {}
			}

			// 20220408 modify by Alan for#109776 : 原屬性名稱為駝峰式命名，後來被改成全大寫
			if (parameter.FASTENINGPACKAGE) {
				parameter.FasteningPackage = parameter.FASTENINGPACKAGE;
			}

			return parameter;
		}
	}];
});
